package main

//Mgo 链接，插入实例
import (
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

type Person struct {
	//`bson:"_id"` 映射到Mongo id字段
	Id   bson.ObjectId `bson:"_id"`
	Name string
	Age  int
}

type Address struct {
	//DBRef 关联表到Person
	DBRef *mgo.DBRef
	Name  string
}

func main() {

	fmt.Println("Start Test Mgo: Insert.......")

	person := &Person{
		Id:   bson.NewObjectId(),
		Name: "Kaibb",
		Age:  24,
	}

	address := &Address{Name: "address", DBRef: &mgo.DBRef{Collection: "people", Id: person.Id}}

	//链接到本地mongodb服务
	session, err := mgo.Dial("mongodb://127.0.0.1:27017")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	fmt.Println(person)
	c := session.DB("Test").C("people")
	a := session.DB("Test").C("address")
	//插入两条数据
	c.Insert(person)
	a.Insert(address)
	p := Person{}
	//根据Name 查找
	c.Find(bson.M{"name": "Kaibb"}).One(&p)
	fmt.Println(p)
	p1 := Person{}
	c.FindId(person.Id).One(&p1)
	fmt.Println(p1)
}
